<template>
  <view class="login-modal" v-if="visible">
    <view class="modal-mask" @tap="onClose"></view>
    <view class="modal-content">
      <view class="modal-header">
        <text class="modal-title">登录提示</text>
        <view class="close-btn" @tap="onClose">×</view>
      </view>
      <view class="modal-body">
        <text class="modal-desc">登录后可以使用更多功能</text>
        <button class="login-btn" @tap="onLogin">微信一键登录</button>
        <view class="skip-btn" @tap="onClose">暂不登录</view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'LoginModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    ...mapActions('user', ['login']),
    onClose() {
      this.$emit('update:visible', false)
    },
    async onLogin() {
      try {
        const userProfile = await new Promise((resolve, reject) => {
          uni.getUserProfile({
            desc: '用于完善用户资料',
            success: res => resolve(res),
            fail: err => reject(err)
          })
        })
        const loginRes = await new Promise((resolve, reject) => {
          uni.login({
            provider: 'weixin',
            success: res => resolve(res),
            fail: err => reject(err)
          })
        })
        await this.login({
          code: loginRes.code,
          avatarUrl: userProfile.userInfo.avatarUrl,
          nickname: userProfile.userInfo.nickName
        })
        uni.showToast({ title: '登录成功', icon: 'success' })
        this.onClose()
      } catch (error) {
        uni.showToast({ title: '未授权无法使用全部功能', icon: 'none' })
      }
    }
  }
}
</script>

<style lang="scss">
.login-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .modal-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
  }
  
  .modal-content {
    position: relative;
    width: 560rpx;
    background: #fff;
    border-radius: 24rpx;
    overflow: hidden;
  }
  
  .modal-header {
    padding: 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 2rpx solid #f5f5f5;
  }
  
  .modal-title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
  }
  
  .close-btn {
    font-size: 40rpx;
    color: #999;
    padding: 0 20rpx;
  }
  
  .modal-body {
    padding: 48rpx 32rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .modal-desc {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 48rpx;
  }
  
  .login-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #07c160;
    color: #fff;
    font-size: 32rpx;
    border-radius: 44rpx;
    margin-bottom: 24rpx;
  }
  
  .skip-btn {
    font-size: 28rpx;
    color: #999;
    padding: 20rpx;
  }
}
</style> 